package com.hkd.common.api.advice;

import com.hkd.common.api.ApiResponse;
import com.hkd.common.api.SysException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {

    public ExceptionAdvice() {
        log.info("全局异常拦截注入");
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ApiResponse<String> exceptionHandler(Exception e){
        log.error("执行异常",e);
        if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exception= (MethodArgumentNotValidException) e;
            //返回精简消息（具体某个字段没有通过校验的原因）
            return ApiResponse.error(exception.getBindingResult().getFieldError().getDefaultMessage());
        }
        else if(e instanceof SysException){
            SysException exception= (SysException) e;
            return ApiResponse.error(exception.getCode(),exception.getMsg());
        }
        else{
            return ApiResponse.error("系统异常");
        }
    }
}
